package com.example.emqx.controller;

import com.example.emqx.entity.ApiResponse;
import com.example.emqx.entity.MybatisOneForOne;
import com.example.emqx.entity.Student;
import com.example.emqx.entity.User;
import com.example.emqx.service.MybatisManyForManyService;
import com.example.emqx.service.MybatisOneForOneService;
import com.example.emqx.service.MybatisOneToManyService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class MybatisController {
    @Autowired
    private MybatisOneForOneService mybatisOneForOneService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private MybatisOneToManyService mybatisOneToManyService;
    @Autowired
    private MybatisManyForManyService mybatisManyForManyService;

    @RequestMapping("/mybatisOneForOne")
    public ApiResponse<List<MybatisOneForOne>> selectList(@RequestParam("pid") String pid) throws JsonProcessingException {
        log.info("selectList pid:{}", pid);
        List<MybatisOneForOne> mybatisOneForOnes = mybatisOneForOneService.selectList(pid);
        log.info("selectList mybatisOneForOnes:{}", objectMapper.writeValueAsString(mybatisOneForOnes));
        return ApiResponse.success(mybatisOneForOnes);
    }

    //http://localhost:9000/mybatisOneToMany?userId=1
    @RequestMapping("/mybatisOneToMany")
    public ApiResponse<User> getUser(@RequestParam("userId") Integer userId) throws JsonProcessingException {
        log.info("getUser userId:{}", userId);
        User user = mybatisOneToManyService.selectOne(userId);
        log.info("selectOne user:{}", objectMapper.writeValueAsString(user));
        return ApiResponse.success(user);
    }

    //MybatisManyForManyServiceImpl
    @RequestMapping("/mybatisManyForMany")
    public ApiResponse<List<Student>> mybatisManyForMany() throws JsonProcessingException {
        List<Student> students = mybatisManyForManyService.selectStudentsWithCourses();
        log.info("students user:{}", objectMapper.writeValueAsString(students));
        return ApiResponse.success(students);

    }
}
